<?php

namespace plugin\ycMassage\app\controller;

use app\common\manager\SettingsMgr;
use plugin\ycMassage\app\BaseController;
use plugin\ycMassage\app\model\MassageNotifyEpay;
use plugin\ycMassage\app\model\MassageNotifyWechat;
use plugin\ycMassage\app\model\MassageOrders;
use plugin\ycMassage\app\model\MassageOrdersSub;
use plugin\ycMassage\app\model\MassageUserDealer;
use plugin\ycMassage\utils\enum\OrdersState;
use plugin\ycMassage\utils\enum\OrdersType;
use plugin\ycMassage\utils\enum\PayType;
use plugin\ycMassage\utils\Epay;
use support\Request;
use think\facade\Db;
use think\facade\Log;
use WeChat\Contracts\Tools;
use WeChat\Exceptions\InvalidResponseException;
use WeChat\Pay;

class NotifyController extends BaseController
{
    public function wechat(Request $request)
    {
        try {
            $logFile = runtime_path('wxnotify') . date('md') . '.log';
            if (!is_dir(dirname($logFile))) {
                mkdir(dirname($logFile), 0777, true);
            }
            file_put_contents($logFile, "微信支付回调\n", FILE_APPEND);
            # 获取通知的数据
            $content = file_get_contents('php://input');
            file_put_contents($logFile, $content . "\n", FILE_APPEND);
            $data = Tools::xml2arr($content);
            if (empty($data['attach'])) {
                throw new InvalidResponseException("平台信息读取错误");
            }
            $saas_appid = (int)$data['attach'];
            $_config = SettingsMgr::getChildren($saas_appid, 'pay');
            if (empty($_config)) {
                throw new \Exception("未配置微信支付");
            }
            $config = [
                // 缓存目录配置（可选，需拥有读写权限）
                'cache_path'     => runtime_path('wxpay'),
            ];
            $config = array_merge($config, [
                'appid' => $data['appid'],
                'mch_id' => $_config['wxpay_mch_id'],
                'mch_key' => $_config['wxpay_mch_key'],
            ]);
            // 创建接口实例
            $wechat = new Pay($config);
            if (isset($data['sign']) && $wechat->getPaySign($data) === $data['sign']) {
                if (MassageNotifyWechat::where(['out_trade_no' => $data['out_trade_no']])->count()) {
                    return xml('<xml> <return_code><![CDATA[SUCCESS]]></return_code> <return_msg><![CDATA[OK]]></return_msg> </xml>');
                }
                Db::startTrans();
                try {
                    $where = [];
                    $where[] = ['trade', '=', $data['out_trade_no']];
                    $Find = MassageOrders::where($where)->find();
                    if ($Find->orders_type === OrdersType::RESERVATION['value']) {
                        $ordersSub = MassageOrdersSub::where(['orders_id' => $Find->id])->select();
                        foreach ($ordersSub as $item) {
                            $item->state = OrdersState::PAY['value'];
                            $item->save();
                        }
                    }
                    $Find->state = OrdersState::PAY['value'];
                    $Find->pay_type = PayType::WXPAY['value'];
                    $Find->pay_time = $data['time_end'];
                    $Find->save();
                    $NotifyWechat = new MassageNotifyWechat;
                    $NotifyWechat->save($data);
                    Db::commit();
                } catch (\Throwable $th) {
                    Db::rollback();
                    throw new InvalidResponseException("订单处理失败");
                }
                MassageOrders::complete($Find->trade);
                return xml('<xml> <return_code><![CDATA[SUCCESS]]></return_code> <return_msg><![CDATA[OK]]></return_msg> </xml>');
            }
            throw new InvalidResponseException('Invalid Notify.');
        } catch (\Throwable $e) {
            // 出错啦，处理下吧
            return xml("<xml> <return_code><![CDATA[FAIL]]></return_code> <return_msg><![CDATA[{$e->getMessage()}]]></return_msg> </xml>");
        }
    }
    public function wechatRefund(Request $request)
    {
        $logFile = runtime_path('wxnotify') . date('md') . '.log';
        if (!is_dir(dirname($logFile))) {
            mkdir(dirname($logFile), 0777, true);
        }
        file_put_contents($logFile, "微信退款回调\n", FILE_APPEND);
        # 获取通知的数据
        $content = file_get_contents('php://input');
        file_put_contents($logFile, $content . "\n", FILE_APPEND);
        return xml('<xml> <return_code><![CDATA[SUCCESS]]></return_code> <return_msg><![CDATA[OK]]></return_msg> </xml>');
    }
    public function epay(Request $request)
    {
        $data = $request->get();
        try {
            $logFile = runtime_path('epay') . date('md') . '.log';
            if (!is_dir(dirname($logFile))) {
                mkdir(dirname($logFile), 0777, true);
            }
            file_put_contents($logFile, "易支付回调\n", FILE_APPEND);
            # 获取通知的数据
            file_put_contents($logFile, json_encode($data, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT) . "\n", FILE_APPEND);
            if ($data['trade_status'] === 'TRADE_SUCCESS') {
                if (MassageNotifyEpay::where(['out_trade_no' => $data['out_trade_no']])->count()) {
                    return $this->success('ok');
                }
                Db::startTrans();
                try {
                    $where = [];
                    $where[] = ['trade', '=', $data['out_trade_no']];
                    $Find = MassageOrders::where($where)->find();

                    $_config = SettingsMgr::getChildren((int)$Find->saas_appid, 'pay');
                    $payment = new Epay([
                        'apiurl' => $_config['epay_url'],
                        'pid' => $_config['epay_appid'],
                        'key' => $_config['epay_appkey'],
                    ]);
                    if (!$payment->verifyNotify()) {
                        throw new InvalidResponseException("签名验证失败");
                    }
                    if ($Find->orders_type === OrdersType::RESERVATION['value']) {
                        $ordersSub = MassageOrdersSub::where(['orders_id' => $Find->id])->select();
                        foreach ($ordersSub as $item) {
                            $item->state = OrdersState::PAY['value'];
                            $item->save();
                        }
                    }
                    $Find->state = OrdersState::PAY['value'];
                    $Find->pay_type = PayType::EPAY['value'];
                    $Find->pay_time = date('Y-m-d H:i:s');
                    $Find->save();
                    $NotifyEpay = new MassageNotifyEpay();
                    $NotifyEpay->save($data);
                    Db::commit();
                } catch (\Throwable $th) {
                    Db::rollback();
                    throw new InvalidResponseException("订单处理失败");
                }
                MassageOrders::complete($Find->trade);
                return $this->success('ok');
            }
        } catch (\Throwable $e) {
            // 出错啦，处理下吧
            return $this->fail($e->getMessage());
        }
    }
    public function winnerlook(Request $request)
    {
        $G=$request->get();
        $D=$request->post();
        Log::info('winnerlook',[$G,$D]);
        return json([
            "resultCode"=>"200"
        ]);
    }
}
